<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="教育集团名称" prop="id">
        <el-select
          v-model="queryParams.id"
          style="width: 200px"
          :filterable="true"
          :clearable="true"
        >
          <el-option
            v-for="item in EdgroupList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学校名称" prop="schoolid">
        <el-input
          v-model="queryParams.name"
          class="icon-search"
          clearable
          placeholder="请输入学校名称"
        >
          <template #suffix
            ><i class="el-icon-search el-input__icon"
          /></template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="schoolList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="序号" width="60" type="index" align="center"/> -->
      <el-table-column label="学校编号" width="300" align="center" prop="id" />
      <!-- show-overflow-tooltip -->
      <el-table-column
        label="教育集团名称"
        width="150"
        align="center"
        prop="edgroup.name"
      >
        <template #default="scope">
          <el-tag v-if="scope.row?.edgroup?.name" type="error">
            {{ scope.row?.edgroup?.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="学校名称"
        show-overflow-tooltip
        align="center"
        prop="name"
      >
        <template #default="scope">
          <el-tag v-if="scope.row?.name" type="primary">
            {{ scope.row?.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="图片"
        show-overflow-tooltip
        align="center"
        prop="photo"
      >
        <template #default="scope">
          <div style="z-index: 10000">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.photo"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              hide-on-click-modal
              preview-teleported
              :preview-src-list="[scope.row.photo]"
              show-progress
              :initial-index="0"
              fit="cover"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        width="280"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Cellphone"
            @click="handleView(scope.row, 'gw')"
            >网关</el-button
          >
          <el-button
            link
            type="primary"
            icon="Cellphone"
            @click="handleView(scope.row, 'wb')"
            >手环</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="SchoolRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        @submit.prevent
      >
        <el-form-item label="教育集团名称" prop="edgroup.id">
          <el-select
            v-model="form.edgroup.id"
            placeholder="请选择教育集团"
            style="width: 260px"
            :filterable="true"
            :clearable="true"
          >
            <el-option
              v-for="edgroup in EdgroupList"
              :key="edgroup.value"
              :label="edgroup.label"
              :value="edgroup.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学校名称" prop="name">
          <el-input
            v-model="form.name"
            class="icon-search"
            clearable
            placeholder="请输入学校名称"
            style="width: 260px"
          >
            <template #suffix
              ><i class="el-icon-search el-input__icon"
            /></template>
          </el-input>
        </el-form-item>
        <el-form-item label="图片" prop="photo">
          <ImageUpload
            :limit="limit"
            list-type="picture-card"
            v-model="form.photo"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 网关弹窗 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="SchoolRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        @submit.prevent
      >
        <el-form-item label="教育集团名称" prop="edgroup.id"> 
          <el-select
            v-model="form.edgroup.id"
            placeholder="请选择教育集团"
            style="width: 260px"
            :filterable="true"
            :clearable="true"
          >
            <el-option
              v-for="edgroup in EdgroupList"
              :key="edgroup.value"
              :label="edgroup.label"
              :value="edgroup.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学校名称" prop="name">
          <el-input
            v-model="form.name"
            class="icon-search"
            clearable
            placeholder="请输入学校名称"  
            style="width: 260px"
          >
            <template #suffix
              ><i class="el-icon-search el-input__icon"
            /></template>
          </el-input>
        </el-form-item>
        <el-form-item label="图片" prop="photo">
          <ImageUpload
            :limit="limit"
            list-type="picture-card"          
            v-model="form.photo"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>  
      </template> 
    </el-dialog>
    <!-- 网关弹窗 -->
    <el-dialog title="网关管理" v-model="openGw" width="90%" append-to-body>
      <gateway 
        :edgroup_id="activeRow.edgroup?.id"
        :school_id="activeRow.id"
        :class_id="null"
      />
    </el-dialog>

    <!-- 手环弹窗 -->
    <el-dialog title="手环管理" v-model="openWb" width="90%" append-to-body>
      <wristband 
        :edgroup_id="activeRow.edgroup?.id"
        :school_id="activeRow.id"
      />
    </el-dialog>
  </div>
</template>

<script setup name="Ota">
import { getFirmwaresList } from "@/api/system/user";
import { getType } from "@/api/system/dict/type";
import { mqttOtaUpgrade } from "@/api/system/firmware/ota";
import {
  getSchoolList,
  getSchoolById,
  updateSchoolById,
  createSchool,
  deleteSchoolById,
} from "@/api/system/school/school";
import { getEdgroupList } from "@/api/system/school/edgroup";
import gateway from "@/views/gateway/index.vue";
import wristband from "@/views/wristband/index.vue";

const { proxy } = getCurrentInstance();
const limit = ref(1);
const { action_ota, firmware_type } = proxy.useDict(
  "action_ota",
  "firmware_type"
);
const openGw = ref(false);
const openWb = ref(false);
const activeRow = ref({});
const options = reactive({
  file: null, // 上传的固件文件
  filename: "firmware", // 默认文件名称
  outputType: "bin", // 默认输出文件类型（例如 .bin 或 .hex）
  previews: {}, // 预览数据（如果需要）
});
/** 覆盖默认上传行为 */
function requestUpload() {}
const EdgroupList = ref();
getEdgroupList().then((res) => {
  EdgroupList.value = res.data.data.map((item) => {
    return {
      label: item.name,
      value: item.id,
      photo: item.photo
    };
  });
});

/** 上传预处理 */
function beforeUpload(file) {
  // 定义允许的固件文件格式
  const allowedFirmwareTypes = [".bin", ".hex"];
  const fileExtension = file.name
    .slice(file.name.lastIndexOf("."))
    .toLowerCase();

  // 校验文件格式
  if (!allowedFirmwareTypes.includes(fileExtension)) {
    proxy.$modal.msgError(
      "文件格式错误，请上传固件类型文件，如：.bin 或 .hex 后缀的文件。"
    );
    return false; // 阻止上传
  }

  // 校验文件大小（例如限制为 10MB）
  const maxSize = 10 * 1024 * 1024; // 10MB
  if (file.size > maxSize) {
    proxy.$modal.msgError("文件大小超过限制，请上传小于 10MB 的文件。");
    return false; // 阻止上传
  }
  // 文件格式和大小都符合要求
  options.file = file; // 存储文件对象
  options.filename = file.name; // 存储文件名
  form.value.name = file.name;
  return true;
}
// console.log(firmware_type);

const schoolList = ref([]);
const firmwaresLists = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const gatewayList = ref([]);
const wristbandList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    name: undefined,
  },
  rules: {
    name: [{ required: true, message: "学校名称不能为空", trigger: "blur" }],
    "edgroup.id": [
      { required: true, message: "教育集团名称不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);
function rawChange(val) {
  if (!val) {
  }
}

/** 查询学校列表 */
function getList() {
  loading.value = true;
  schoolList.value = [];
  // console.log('queryParams.value', queryParams.value)
  getSchoolList(queryParams.value).then((response) => {
    // console.log("学校列表", response.data);
    schoolList.value = response.data.data;
    total.value = response.data.total;
    loading.value = false;
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getSchoolById(id).then((response) => {
    console.log(response);
    form.value = response.data;
    open.value = true;
    title.value = "修改学校";
  });
}

// 固件列表
function getFirmwaresLists() {
  getFirmwaresList().then((response) => {
    // console.log("固件列表",response);
    const { data, msg, code } = response;
    if (code === 200) {
      firmwaresLists.value = data;
    } else {
      firmwaresLists.value = [];
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    name: "", //
    photo: "",
    edgroup: {
      id: null,
      name: "", //
      photo: "",
    },
  };
  proxy.resetForm("SchoolRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增学校";
}

/** OTA任务选择固件 带出固件类型 */
function firmwareChange(value) {
  form.value.firmwareType = value.firmwareType;
  form.value.schoolid = value.id;
  form.value.full = 0;
  form.value.gw_mac = "";
  form.value.gw_full = 0;
  form.value.wb_mac = "";
  form.value.wb_full = 0;
  form.value.force = false;
  form.value.remain = false;
}

function forceChange(val) {
  if (!val) {
  }
}

function remainChange(val) {
  if (!val) {
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["SchoolRef"].validate((valid) => {
    if (valid) {
      form.value.edgroup.name = EdgroupList.value.find((item)=> item.value == form.value.edgroup.id).label
      form.value.edgroup.photo = EdgroupList.value.find((item)=> item.value == form.value.edgroup.id).photo
      console.log(111, form.value);
      if (form.value.id != undefined) {
        // console.log(form.value);
        updateSchoolById(form.value).then((response) => {
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError("修改失败");
          }
        });
      } else {
        // console.log('add', form.value);
        createSchool(form.value).then((response) => {
          // console.log(response);
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError("新增失败");
          }
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除编号为"' + ids + '"的数据项？')
    .then(function () {
      return deleteSchoolById(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

function handleView(row, type) {
  activeRow.value = row;
  console.log("查看操作", activeRow.value, type);
  if (!ids) {
    proxy.$modal.msgError("请选择要查看的学校");
    return;
  }
  switch (type) {
    case "gw":
      openGw.value = true;
      break;
    case "wb":
      openWb.value = true;
      break;
    default:
      proxy.$modal.msgError("未知操作类型");
      break;
  }
}

/** 修改操作 */
function handleEdit(row) {
  const params = {
    taskId: row.id,
    schoolid: row.schoolid,
    localPath: row.path,
    force: row.force || false,
  };
  proxy.$modal
    .confirm(`是否现在升级任务编号为 ${row.id} 的任务？`)
    .then(function () {
      return mqttOtaUpgrade(params);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("开始升级");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  /*proxy.download("system/post/export", {
    ...queryParams.value
  }, `post_${new Date().getTime()}.xlsx`);*/
}

getFirmwaresLists();
getList();
</script>

<style scoped>
.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
</style>
